package com.xyl.user.service;

import com.alibaba.fastjson.JSON;
import com.xyl.common.cache.RedisCacheManager;
import com.xyl.common.constants.Constants;
import com.xyl.common.utils.RandomNumberCode;
import com.xyl.jms.QueueSender;
import com.xyl.jms.SmsProcessor;
import com.xyl.user.dao.UserMapper;
import com.xyl.user.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service("userServiceImpl")
public class UserServiceImpl implements UserService {
    private static final String SMS_QUEUE = "xqw.queue";

    @Autowired
    private QueueSender queueSender;

    @Autowired
    private SmsProcessor smsProcessor;

    @Autowired
    private RedisCacheManager redisCacheManager;

    @Autowired
    private UserMapper userMapper;

    @Override
    public int registerUser(User user) {

        int i = userMapper.insertSelective(user);
        return i;
    }

    @Override
    public boolean checkName(String name) {
        User user = userMapper.selectByName(name);
        if (user != null) {
            return true;
        }
        return false;
    }

    @Override
    public int sendVercode(Long phone, String ip) {
        String verCode = RandomNumberCode.verCode();
        // 验证此ip是否多次请求  产生随机验证码
        int result = -1;
        try {
            result = redisCacheManager.cacheForVerificationCode("phone." + phone.toString(), verCode, "reg", 120, ip);
        } catch (Exception e) {
            if (result == 1) {
                //返回json数据  进行操作
                log.error("redis error:", e);
            } else if (result == 2) {
                log.error("redis error:", e);
            } else if (result == 3) {
                log.error("redis error:", e);
            } else if (result == -1) {
                log.error("redis error:", e);
            }
            return -1;
        }

        try {
            //根据AMQ消息队列 将短信异步出去  进行短信发送操作
            Map<String, String> map = new HashMap();
            map.put("mobile", phone.toString());
            map.put("tplId", Constants.MDSMS_VERCODE_TPLID);
            map.put("vercode", verCode);
            String message = JSON.toJSONString(map);
            queueSender.send(SMS_QUEUE, message);
        } catch (Exception e) {
            log.error("AMQ error:",e);
            return -1;
        }
        return 1;
    }

}
